import random
import string
from io import BytesIO

from PIL import Image, ImageDraw, ImageFont
from flask import g

from application import db
from web.models.boke_models import Collection, QuestionModel, Like


# 生成图片验证码
class ImageCode:
    # 随机字符串
    def get_text(self):
        list = ''.join(random.sample(string.ascii_uppercase + string.digits, 4))
        return list

    # 随机颜色
    def rand_color(self):
        red = random.randint(32, 127)
        green = random.randint(32, 127)
        blue = random.randint(32, 127)
        return red, green, blue

    # 干扰线
    def draw_lines(self, draw, num, width, height):
        for num in range(num):
            x1 = random.randint(0, width / 2)
            y1 = random.randint(0, height / 2)
            x2 = random.randint(0, width)
            y2 = random.randint(height / 2, height)
            draw.line(((x1, y1), (x2, y2)), fill='black', width=2)

    # 绘制验证码图片
    def draw_code(self):
        code = self.get_text()
        width, height = 120, 50
        im = Image.new('RGB', (width, height), 'white')
        # 选择使用字体、大小
        font = ImageFont.truetype(font='/root/data/zm/static/font/arial.ttf', size=40)
        draw = ImageDraw.Draw(im)
        # 绘制字符串
        for i in range(4):
            draw.text((5 + random.randint(-3, 3) + 23 * i, random.randint(-3, 3)), text=code[i], fill=self.rand_color(),
                      font=font)
        # 绘制干扰线
        self.draw_lines(draw, 4, width, height)
        return im, code

    # 生成图片验证码并返回给控制器
    def get_code(self):
        image, code = self.draw_code()
        buf = BytesIO()
        image.save(buf, 'jpeg')
        bstring = buf.getvalue()  # 图片值
        return code, bstring


# 判断是不是已经被收藏
def check_favorite(id):
    try:
        favorite = Collection.query.filter_by(author_id=g.user.id, question_id=id).first()
        if favorite is None:
            return False
        elif int(favorite.canceled) == 1:
            return False
        else:
            return True
    except:
        return False


# 上一篇和下一篇
def up_and_down(id):
    dic = {}
    # 比当前小的最大的一篇
    questions = QuestionModel.query.filter(QuestionModel.draft == 0, QuestionModel.check == 1,
                                           QuestionModel.hidden == 0, QuestionModel.id < id
                                           ).order_by(QuestionModel.id.desc()).first()
    if questions:
        pre_id = questions.id
    else:
        pre_id = id
    dic['pre_id'] = pre_id
    dic['pre_title'] = QuestionModel.query.filter_by(id=pre_id).first().title

    # 比当前大的最小的一篇
    question_down = QuestionModel.query.filter(QuestionModel.draft == 0, QuestionModel.check == 1,
                                               QuestionModel.hidden == 0, QuestionModel.id > id
                                               ).order_by(QuestionModel.id).first()
    if question_down:
        beh_id = question_down.id
    else:
        beh_id = id
    dic['beh_id'] = beh_id
    dic['beh_title'] = QuestionModel.query.filter_by(id=beh_id).first().title
    return dic


# 给文章点赞
def support(article_id):
    if g.user:
        article = QuestionModel.query.filter_by(id=article_id).first()
        article.up += 1
        judge_like = Like.query.filter_by(user_id=g.user.id, article_id=article_id, type=0).first()
        if not judge_like:
            like = Like(user_id=g.user.id, article_id=article_id, type=1)
            db.session.add(like)
        else:
            judge_like.type = 1
        db.session.add(article)
        db.session.commit()
    else:
        return False

# 取消点赞
def cancle_support(article_id):
    if g.user:
        article = QuestionModel.query.filter_by(id=article_id).first()
        if article.up > 0:
            article.up -= 1
        like = Like.query.filter_by(user_id=g.user.id, article_id=article_id).first()
        like.type = 0
        db.session.add(like)
        db.session.add(article)
        db.session.commit()

    else:
        return False

# 给文章点踩
def oppose(article_id):
    if g.user:
        article = QuestionModel.query.filter_by(id=article_id).first()
        article.down += 1
        judge_like = Like.query.filter_by(user_id=g.user.id, article_id=article_id, type=0).first()
        if not judge_like:
            dlike = Like(user_id=g.user.id, article_id=article_id, type=2)
            db.session.add(dlike)
        else:
            judge_like.type = 2
        db.session.add(article)
        db.session.commit()

    else:
        return False

# 取消点踩
def cancel_oppose(article_id):
    if g.user:
        article = QuestionModel.query.filter_by(id=article_id).first()
        if article.down>0:
            article.down -= 1
        dlike = Like.query.filter_by(user_id=g.user.id, article_id=article_id, type=2).first()
        dlike.type = 0
        db.session.add(dlike)
        db.session.add(article)
        db.session.commit()

    else:
        return False


